import router from "./router";

import nprogress from "nprogress"
import "nprogress/nprogress.css"
nprogress.configure({ showSpinner: false });

import useUserStore from "./store/modules/user";
import pinia from "./store";

const userStore = useUserStore(pinia);

//全局前置导航守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  document.title = '成峰-' + to.meta.title
  //判断用户是否登录
  if (userStore.token) {
    if (to.path === "/login") {
      next({ path: "/" });
    } else {
      if (userStore.userName) {
        next();
      } else {
        //获取用户信息
        try {
          await userStore.getUserInfo();
          next();
        } catch (error) {
          // 退出 token过期
          await userStore.userLogout();
          next({ path: "/login", query: { redirect: to.path } });
        }
      }
    }
  } else {
    //判断是否是登录页面
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

//全局后置导航守卫
router.afterEach(() => {
  nprogress.done()
});